/*
 * Ania2View.java
 */
package ania2;

import ania2.engine.AdvancedPositionEstimator;
import ania2.engine.Engine2;
import ania2.engine.PositionEstimator;
import ania2.engine.utils.TranspositionTable;
import ania2.gui.GameRecordCellRenderer;
import ania2.gui.GameRecordTableModel;
import ania2.gui.MoveEstimationTableModel;
import ania2.gui.NewGameDialog;
import ania2.gui.RowHeaderCellRenderer;
import java.awt.Dimension;
import org.jdesktop.application.Action;
import org.jdesktop.application.ResourceMap;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.FrameView;
import org.jdesktop.application.TaskMonitor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import java.util.concurrent.ExecutionException;
import javax.swing.Timer;
import javax.swing.Icon;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableCellRenderer;

/**
 * The application's main frame.
 */
public class Ania2View extends FrameView {

    private BoardManager boardListener;
    private MoveGenerator moveGenerator;
    private boolean whiteTurn;
    private Engine2 engine1;
    private TranspositionTable whiteTranspositionTable;
    private TranspositionTable blackTranspositionTable;
    private PositionEstimator positionEstimator;
    private GameManager gameManager;
    private AbstractTableModel tableModel;
    private AbstractTableModel moveEstimationTableModel;
    private int timePerMove;
    private boolean computerPlaysWhite;
    private boolean computerPlaysBlack;

    public Ania2View(SingleFrameApplication app) {
        super(app);

        initComponents();
        initOther();
        // status bar initialization - message timeout, idle icon and busy animation, etc
        ResourceMap resourceMap = getResourceMap();
        int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
        messageTimer = new Timer(messageTimeout, new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                statusMessageLabel.setText("");
            }
        });
        messageTimer.setRepeats(false);
        int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
        for (int i = 0; i < busyIcons.length; i++) {
            busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
        }
        busyIconTimer = new Timer(busyAnimationRate, new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
                statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
            }
        });
        idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
        statusAnimationLabel.setIcon(idleIcon);
        progressBar.setVisible(false);

        // connecting action tasks to status bar via TaskMonitor
        TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());
        taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() {

            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                String propertyName = evt.getPropertyName();
                if ("started".equals(propertyName)) {
                    if (!busyIconTimer.isRunning()) {
                        statusAnimationLabel.setIcon(busyIcons[0]);
                        busyIconIndex = 0;
                        busyIconTimer.start();
                    }
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(true);
                } else if ("done".equals(propertyName)) {
                    busyIconTimer.stop();
                    statusAnimationLabel.setIcon(idleIcon);
                    progressBar.setVisible(false);
                    progressBar.setValue(0);
                } else if ("message".equals(propertyName)) {
                    String text = (String) (evt.getNewValue());
                    statusMessageLabel.setText((text == null) ? "" : text);
                    messageTimer.restart();
                } else if ("progress".equals(propertyName)) {
                    int value = (Integer) (evt.getNewValue());
                    progressBar.setVisible(true);
                    progressBar.setIndeterminate(false);
                    progressBar.setValue(value);
                }
            }
        });
    }

    @Action
    public void showAboutBox() {
        if (aboutBox == null) {
            JFrame mainFrame = Ania2App.getApplication().getMainFrame();
            aboutBox = new Ania2AboutBox(mainFrame);
            aboutBox.setLocationRelativeTo(mainFrame);
        }
        Ania2App.getApplication().show(aboutBox);
    }

    @Action
    public void showNewGameDialog() {
        if (newGameDialog == null) {
            JFrame mainFrame = Ania2App.getApplication().getMainFrame();
            newGameDialog = new NewGameDialog(mainFrame, true);
            newGameDialog.setLocationRelativeTo(mainFrame);
        }
        Ania2App.getApplication().show(newGameDialog);
        int selectedValue = newGameDialog.getValue();
        if (selectedValue == newGameDialog.OK_OPTION) {
            this.whiteTurn = newGameDialog.iswhiteTurn();
            this.timePerMove = newGameDialog.getTimePerMove();
            this.computerPlaysWhite = newGameDialog.isComputerPlayingWhites();
            this.computerPlaysBlack = newGameDialog.isComputerPlayingBlacks();
            board1.setPosition(newGameDialog.getPosition());
            board1.repaint();
            gameManager = new GameManager(board1.getPosition());
            tableModel = new GameRecordTableModel(gameManager.getMovesList());
            jTable1.setModel(tableModel);
            jTable1.getColumnModel().getColumn(0).setCellRenderer(new RowHeaderCellRenderer());
            TableCellRenderer cellRenderer = new GameRecordCellRenderer();
            jTable1.getColumnModel().getColumn(1).setCellRenderer(cellRenderer);
            jTable1.getColumnModel().getColumn(2).setCellRenderer(cellRenderer);
            whiteTranspositionTable = new TranspositionTable();
            blackTranspositionTable = new TranspositionTable();
            if ((whiteTurn && !computerPlaysWhite) || (!whiteTurn && !computerPlaysBlack)) {//ruch gracza
                boardListener.setPossibleMoves(moveGenerator.generateMoves(board1.getPosition(), whiteTurn));
                board1.setEnabled(true);
            } else {//ruch programu
                board1.setEnabled(false);
                engine1 = new MyEngine(board1.getPosition(), whiteTurn, timePerMove,
                        whiteTranspositionTable, blackTranspositionTable, positionEstimator);
                engine1.execute();
            }
        }
    }

    private void initOther() {
        positionEstimator = new AdvancedPositionEstimator();
        BoardPosition boardPosition = new BoardPosition();
        boardPosition.setStandardBeginingPosition();
        boardPosition.computeHashAndLockCode();
        board1.setPosition(boardPosition);
        board1.repaint();
        gameManager = new GameManager();
        moveGenerator = new BrazilianMoveGenerator2();
        boardListener = new BoardManager(board1, board1.getBorderWidth(), board1.getWidth());
        board1.addMouseListener(boardListener);
        whiteTurn = true;
        boardListener.setPossibleMoves(moveGenerator.generateMoves(boardPosition, whiteTurn));
        boardListener.addPropertyChangeListener(new java.beans.PropertyChangeListener() {

            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                if (evt.getPropertyName().equals("selectedField")) {
                    board1.setFieldsWithHighlightedFrame(boardListener.getAffectedFields());
                    board1.repaint();
                } else if (evt.getPropertyName().equals("moveExecuted")) {
                    Move m = boardListener.getLastMove();
                    //gameManager.addMove(m);
                    if (addMove(m)) {
                        board1.setEnabled(false);
                        tableModel.fireTableDataChanged();
                        board1.setPosition(m.getPosition());
                        whiteTurn = !whiteTurn;
                        board1.repaint();
                        if ((whiteTurn && !computerPlaysWhite) || (!whiteTurn && !computerPlaysBlack)) {//ruch gracza
                            List<Move> possibleMoves = moveGenerator.generateMoves(board1.getPosition(), whiteTurn);
                            if (possibleMoves.isEmpty()) {
                                endOfGame(whiteTurn);
                            }
                            boardListener.setPossibleMoves(possibleMoves);
                            board1.setEnabled(true);
                        } else {
                            engine1 = new MyEngine(m.getPosition(), whiteTurn, timePerMove, whiteTranspositionTable,
                                    blackTranspositionTable, positionEstimator);
                            engine1.execute();
                        }
                    }
                    board1.getFieldsWithHighlightedFrame().clear();
                    board1.repaint();
                }
            }
        });
        whiteTranspositionTable = new TranspositionTable();
        blackTranspositionTable = new TranspositionTable();
        tableModel = new GameRecordTableModel(gameManager.getMovesList());
        jTable1.setModel(tableModel);
        jTable1.getColumnModel().getColumn(0).setCellRenderer(new RowHeaderCellRenderer());
        TableCellRenderer cellRenderer = new GameRecordCellRenderer();
        jTable1.getColumnModel().getColumn(1).setCellRenderer(cellRenderer);
        jTable1.getColumnModel().getColumn(2).setCellRenderer(cellRenderer);
        moveEstimationTableModel = new MoveEstimationTableModel();
        jTable2.setModel(moveEstimationTableModel);
        jTable2.getColumnModel().getColumn(0).setCellRenderer(new RowHeaderCellRenderer());
        jTable2.getColumnModel().getColumn(1).setCellRenderer(cellRenderer);
        jTable2.getColumnModel().getColumn(2).setCellRenderer(cellRenderer);
        timePerMove = 3000;
        computerPlaysWhite = false;
        computerPlaysBlack = true;
    }

    private boolean addMove(Move m) {
        Move nextMove = gameManager.nextMove();
        if (nextMove != null) {
            gameManager.previousMove();
        }
        if (!gameManager.isEndOfMovesList() && !m.equals(nextMove)) {
            JFrame mainFrame = Ania2App.getApplication().getMainFrame();
            JOptionPane pane = new JOptionPane("Czy nadpisać bieżącą kontynuację gry?", JOptionPane.QUESTION_MESSAGE, JOptionPane.YES_NO_OPTION);
            JDialog dialog = pane.createDialog(mainFrame, "Potwierdź nadpisanie");
            dialog.setVisible(true);
            Object selectedValue = pane.getValue();
            if (selectedValue == null) {
                return false;
            }
            if (selectedValue instanceof Integer) {
                int i = ((Integer) selectedValue).intValue();
                if (i == JOptionPane.NO_OPTION) {
                    return false;
                }
            }
        }
        gameManager.addMove(m);
        return true;
    }

    private void endOfGame(boolean whiteTurn) {
        JFrame mainFrame = Ania2App.getApplication().getMainFrame();
        String message = (whiteTurn) ? "Czarne wygrały" : "Białe wygrały";
        JOptionPane.showMessageDialog(mainFrame, message);

    }

    private class MyEngine extends Engine2 {

        public MyEngine(BoardPosition position, boolean whiteTurn, int availableTime,
                TranspositionTable white, TranspositionTable black, PositionEstimator positionEstimator) {
            super(position, whiteTurn, availableTime, white, black, positionEstimator);
        }

        @Override
        protected Move doInBackground() throws Exception {
            if (busyIconTimer != null) {
                busyIconTimer.start();
            }
            board1.setEnabled(false);
            return super.doInBackground();
        }

        @Override
        protected void done() {
            super.done();
            try {
                if (busyIconTimer != null) {
                    busyIconTimer.stop();
                }
                Move m = get();
                if (m == null) {
                    endOfGame(whiteTurn);
                }
                if (addMove(m)) {
                    tableModel.fireTableDataChanged();
                    board1.setPosition(m.getPosition());
                    board1.repaint();
                    whiteTurn = !whiteTurn;
                    if ((whiteTurn && !computerPlaysWhite) || (!whiteTurn && !computerPlaysBlack)) {//ruch gracza
                        List<Move> possibleMoves = moveGenerator.generateMoves(board1.getPosition(), whiteTurn);
                        if (possibleMoves.isEmpty()) {
                            endOfGame(whiteTurn);
                        }
                        boardListener.setPossibleMoves(possibleMoves);
                        board1.setEnabled(true);
                    } else {
                        engine1 = new MyEngine(m.getPosition(), whiteTurn, timePerMove, whiteTranspositionTable,
                                blackTranspositionTable, positionEstimator);
                        engine1.execute();
                    }
                }
            } catch (InterruptedException ignore) {
            } catch (NullPointerException e) {
            } catch (ExecutionException e) {
                String why = null;
                Throwable cause = e.getCause();
                if (cause != null) {
                    why = cause.getMessage();
                } else {
                    why = e.getMessage();
                }
                System.err.println("Error: " + why);
                e.printStackTrace();
            }
        //System.out.println(whiteTranspositionTable.keySet().size());
        }

        @Override
        protected void process(List<List<Move>> chunks) {
            //super.process(chunks);
            ((MoveEstimationTableModel) moveEstimationTableModel).setDataList(
                    chunks.get(chunks.size() - 1));
            moveEstimationTableModel.fireTableDataChanged();
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        mainPanel = new javax.swing.JPanel();
        board1 = new ania2.draughtsboard.Board();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jButton5 = new javax.swing.JButton();
        jButton6 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTable2 = new javax.swing.JTable();
        menuBar = new javax.swing.JMenuBar();
        javax.swing.JMenu fileMenu = new javax.swing.JMenu();
        jMenuItem1 = new javax.swing.JMenuItem();
        javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem();
        javax.swing.JMenu helpMenu = new javax.swing.JMenu();
        javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem();
        statusPanel = new javax.swing.JPanel();
        javax.swing.JSeparator statusPanelSeparator = new javax.swing.JSeparator();
        statusMessageLabel = new javax.swing.JLabel();
        statusAnimationLabel = new javax.swing.JLabel();
        progressBar = new javax.swing.JProgressBar();

        mainPanel.setName("mainPanel"); // NOI18N

        board1.setName("board1"); // NOI18N
        board1.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                board1PropertyChange(evt);
            }
        });

        javax.swing.GroupLayout board1Layout = new javax.swing.GroupLayout(board1);
        board1.setLayout(board1Layout);
        board1Layout.setHorizontalGroup(
            board1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 315, Short.MAX_VALUE)
        );
        board1Layout.setVerticalGroup(
            board1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 686, Short.MAX_VALUE)
        );

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(ania2.Ania2App.class).getContext().getResourceMap(Ania2View.class);
        jButton2.setText(resourceMap.getString("jButton2.text")); // NOI18N
        jButton2.setName("jButton2"); // NOI18N
        jButton2.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                jButton2MousePressed(evt);
            }
        });

        jButton3.setText(resourceMap.getString("jButton3.text")); // NOI18N
        jButton3.setName("jButton3"); // NOI18N
        jButton3.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                jButton3MousePressed(evt);
            }
        });

        jButton5.setText(resourceMap.getString("jButton5.text")); // NOI18N
        jButton5.setName("jButton5"); // NOI18N
        jButton5.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                jButton5MousePressed(evt);
            }
        });

        jButton6.setText(resourceMap.getString("jButton6.text")); // NOI18N
        jButton6.setName("jButton6"); // NOI18N
        jButton6.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                jButton6MousePressed(evt);
            }
        });

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jTable1.setName("jTable1"); // NOI18N
        jTable1.getTableHeader().setReorderingAllowed(false);
        jScrollPane1.setViewportView(jTable1);

        jScrollPane2.setName("jScrollPane2"); // NOI18N

        jTable2.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jTable2.setName("jTable2"); // NOI18N
        jScrollPane2.setViewportView(jTable2);

        javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
        mainPanel.setLayout(mainPanelLayout);
        mainPanelLayout.setHorizontalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, mainPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(board1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(jScrollPane2, 0, 0, Short.MAX_VALUE)
                    .addComponent(jScrollPane1, 0, 0, Short.MAX_VALUE)
                    .addGroup(mainPanelLayout.createSequentialGroup()
                        .addComponent(jButton2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton5)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton6)))
                .addContainerGap())
        );
        mainPanelLayout.setVerticalGroup(
            mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(mainPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(board1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(mainPanelLayout.createSequentialGroup()
                        .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jButton6)
                            .addComponent(jButton5)
                            .addComponent(jButton3)
                            .addComponent(jButton2))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 274, Short.MAX_VALUE)
                        .addGap(6, 6, 6)
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 363, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap())))
        );

        menuBar.setName("menuBar"); // NOI18N

        fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N
        fileMenu.setName("fileMenu"); // NOI18N

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(ania2.Ania2App.class).getContext().getActionMap(Ania2View.class, this);
        jMenuItem1.setAction(actionMap.get("showNewGameDialog")); // NOI18N
        jMenuItem1.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_N, java.awt.event.InputEvent.CTRL_MASK));
        jMenuItem1.setText(resourceMap.getString("jMenuItem1.text")); // NOI18N
        jMenuItem1.setName("jMenuItem1"); // NOI18N
        fileMenu.add(jMenuItem1);

        exitMenuItem.setAction(actionMap.get("quit")); // NOI18N
        exitMenuItem.setName("exitMenuItem"); // NOI18N
        fileMenu.add(exitMenuItem);

        menuBar.add(fileMenu);

        helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N
        helpMenu.setName("helpMenu"); // NOI18N

        aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N
        aboutMenuItem.setName("aboutMenuItem"); // NOI18N
        helpMenu.add(aboutMenuItem);

        menuBar.add(helpMenu);

        statusPanel.setName("statusPanel"); // NOI18N

        statusPanelSeparator.setName("statusPanelSeparator"); // NOI18N

        statusMessageLabel.setName("statusMessageLabel"); // NOI18N

        statusAnimationLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        statusAnimationLabel.setName("statusAnimationLabel"); // NOI18N

        progressBar.setName("progressBar"); // NOI18N

        javax.swing.GroupLayout statusPanelLayout = new javax.swing.GroupLayout(statusPanel);
        statusPanel.setLayout(statusPanelLayout);
        statusPanelLayout.setHorizontalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(statusPanelSeparator, javax.swing.GroupLayout.DEFAULT_SIZE, 565, Short.MAX_VALUE)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(statusMessageLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 381, Short.MAX_VALUE)
                .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(statusAnimationLabel)
                .addContainerGap())
        );
        statusPanelLayout.setVerticalGroup(
            statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(statusPanelLayout.createSequentialGroup()
                .addComponent(statusPanelSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(statusMessageLabel)
                    .addComponent(statusAnimationLabel)
                    .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(3, 3, 3))
        );

        setComponent(mainPanel);
        setMenuBar(menuBar);
        setStatusBar(statusPanel);
    }// </editor-fold>//GEN-END:initComponents

private void board1PropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_board1PropertyChange
// TODO add your handling code here:
    String property = evt.getPropertyName();
    if (property.equals("size")) {
        if (evt.getNewValue() instanceof Dimension) {
            Dimension d = (Dimension) evt.getNewValue();
            boardListener.updateBoardSize(d.width);
        }
    } else if (property.equals("borderWidth")) {
        if (evt.getNewValue() instanceof Integer) {
            int newValue = (Integer) evt.getNewValue();
            boardListener.setBorder(newValue);
        }
    }
}//GEN-LAST:event_board1PropertyChange

private void jButton2MousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton2MousePressed
    try {
        board1.setEnabled(true);
        Move m = gameManager.rewindBackward();
        whiteTurn = gameManager.isWhiteTurn();
        board1.setPosition(m.getPosition());
        board1.repaint();
        boardListener.setPossibleMoves(moveGenerator.generateMoves(m.getPosition(), whiteTurn));
    } catch (NullPointerException e) {
    }
}//GEN-LAST:event_jButton2MousePressed

private void jButton5MousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton5MousePressed
    try {
        board1.setEnabled(true);
        Move m = gameManager.nextMove();
        whiteTurn = gameManager.isWhiteTurn();
        board1.setPosition(m.getPosition());
        board1.repaint();
        boardListener.setPossibleMoves(moveGenerator.generateMoves(m.getPosition(), whiteTurn));
    } catch (NullPointerException e) {
        //e.printStackTrace();
    }
}//GEN-LAST:event_jButton5MousePressed

private void jButton3MousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton3MousePressed
    try {
        board1.setEnabled(true);
        Move m = gameManager.previousMove();
        whiteTurn = gameManager.isWhiteTurn();
        board1.setPosition(m.getPosition());
        board1.repaint();
        boardListener.setPossibleMoves(moveGenerator.generateMoves(m.getPosition(), whiteTurn));
    } catch (NullPointerException e) {
        //e.printStackTrace();
    }
}//GEN-LAST:event_jButton3MousePressed

private void jButton6MousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton6MousePressed
    try {
        board1.setEnabled(true);
        Move m = gameManager.rewindForward();
        whiteTurn = gameManager.isWhiteTurn();
        board1.setPosition(m.getPosition());
        board1.repaint();
        boardListener.setPossibleMoves(moveGenerator.generateMoves(m.getPosition(), whiteTurn));
    } catch (NullPointerException e) {
    }
}//GEN-LAST:event_jButton6MousePressed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private ania2.draughtsboard.Board board1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton5;
    private javax.swing.JButton jButton6;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable jTable1;
    private javax.swing.JTable jTable2;
    private javax.swing.JPanel mainPanel;
    private javax.swing.JMenuBar menuBar;
    private javax.swing.JProgressBar progressBar;
    private javax.swing.JLabel statusAnimationLabel;
    private javax.swing.JLabel statusMessageLabel;
    private javax.swing.JPanel statusPanel;
    // End of variables declaration//GEN-END:variables
    private final Timer messageTimer;
    private final Timer busyIconTimer;
    private final Icon idleIcon;
    private final Icon[] busyIcons = new Icon[15];
    private int busyIconIndex = 0;
    private JDialog aboutBox;
    private NewGameDialog newGameDialog;
}
